//
//  main.c
//  wireless_sensor
//
//  Created by fukai on 2018/11.
//  Copyright © 2018年 赛博智能车实验室. All rights reserved.
//

#include "stm32f10x.h"
#include "tick_timer.h"
#include "key.h"
#include "oled.h"
#include "led.h"
#include "beep.h"
#include "dh11.h"
#include "nrf24l01.h"
#include "wireless_os.h"
#include "timer_interrupt.h"


//#define MASTER
#define SLAVE

//定义主循环状态机(Master & Slave)
//主机状态机
typedef enum
{
	MASTER_RECEIVE_INFO,	//接收从机信息
	MASTER_ANALYZE_INFO,	//信息分析
	MASTER_SHOW_INFO,		//信息显示
}MasterStatusNode;

//从机状态机
typedef enum
{
	SLAVE_GET_INFO = 0,		//温湿度采集
	SLAVE_ANALYZE_INFO,		//信息分析
	SLAVE_SHOW_INFO,		//信息显示
	SLAVE_SEND_INFO,		//发送信息给主机
}SlaveStatusNode;


//硬件初始化
void BoardInit(void)
{
	// 设置中断优先级分组2
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	
	//基础硬件初始化
	DelayInit();
	OledInit();
	LedInit();
	BeepInit();
	Tim2IntInit(10-1,7199);	//3ms一次中断  72000000/7200=10kHZ 
	
	#ifdef SLAVE
	//DHT11初始化
	while(DHT11Init())
	{
		BeepWork();
		OledShow6x8Str(10,3,"Sensor error!!");
	}
	OledCls();
	BeepStop();
	OledShow6x8Str(10,3,"Sensor OK!!");
	#endif
	
	//NRF24L01初始化
	Nrf24l01Init();
	while(Nrf24l01Check())
	{
		BeepWork();
		OledShow6x8Str(10,4,"NRF24L01 error!!");
	}
	OledCls();
	BeepStop();
	OledShow6x8Str(10,4,"NRF24L01 OK!!");
	 
	OledCls();
}

int main()
{
	BoardInit();
	
	#ifdef MASTER
	MasterStatusNode MasterStatus;
	while(1)
	{
		switch(MasterStatus)
		{
			case MASTER_RECEIVE_INFO://接收从机信息
				Nrf24l01RxMode();
				DelayMs(50);
				if(Nrf24l01RxPacket(WiSenMaster.data_buffer) == 0)
				{
					WiSenMaster.DataReceiveStatus = RECEIVE_OK;
				}
				else
				{
					WiSenMaster.DataReceiveStatus = RECEIVE_FAILD;
				}
				MasterDataBufferUpdate();
				MasterStatus = MASTER_ANALYZE_INFO;
				break;
			
			case MASTER_ANALYZE_INFO://信息分析
				MasterDataAnalysis();
				MasterStatus = MASTER_SHOW_INFO;
				break;
			
			case MASTER_SHOW_INFO://信息显示
				MasterUserInterface();
				MasterStatus = MASTER_RECEIVE_INFO;
				break;
		}
	}
	
	#endif
	
	#ifdef SLAVE
	SlaveStatusNode SlaveStatus = SLAVE_GET_INFO;	//初始化主状态机为温湿度采集
	while(1)
	{
		switch(SlaveStatus)
		{
			case SLAVE_GET_INFO://信息采集
				DHT11ReadData(&WiSenSlave.temperature,&WiSenSlave.humidity);
				if((WiSenSlave.temperature!=0)&&(WiSenSlave.humidity!=0))
				{
					SlaveStatus = SLAVE_ANALYZE_INFO;	
				}
				break;
				
			case SLAVE_ANALYZE_INFO://信息分析
				DataAnalysis();
				SlaveStatus = SLAVE_SHOW_INFO;
				break;
			
			case SLAVE_SHOW_INFO://信息显示
				user_interface();
				SlaveStatus = SLAVE_SEND_INFO;
				break;
			
			case SLAVE_SEND_INFO://信息传出
				DataBufferUpdate();//传感器数据缓冲区更新
				Nrf24l01TxMode();
				if(Nrf24l01TxPacket(WiSenSlave.data_buffer) == TX_OK)
				{
					WiSenSlave.DataSendStatus = SEND_OK;
				}
				else
				{
					WiSenSlave.DataSendStatus = SEND_FAILD;
				}
				SlaveStatus = SLAVE_GET_INFO;
				break;
		}	
	}
	#endif
}











